package com.gzh.spring.servlet;


import com.gzh.spring.serivce.TestService;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description:
 * @package: com.gzh.spring.servlet
 * @Auther: Pf.Guo
 * @Date: Created in 2021/1/17 17:15
 */

@WebServlet(urlPatterns = "/test")
public class TestServlet extends HttpServlet {

    private TestService testService;

    @Override
    public void init() throws ServletException {
        WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        testService = (TestService) webApplicationContext.getBean("testService");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        System.out.println("执行test方法前……");
        String test = testService.test();
        System.out.println("执行完test方法……");
        // 响应
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().print(test);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
